package com.easylinkin.linkappapi.meterbilling.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.elasticsearch.entity.ESconfig;
import com.easylinkin.linkappapi.elasticsearch.util.EsCalendar;
import com.easylinkin.linkappapi.meterbilling.entity.EnergyConsumption;
import com.easylinkin.linkappapi.meterbilling.entity.MeterDeviceConfig;
import com.easylinkin.linkappapi.meterbilling.service.EnergyConsumptionService;
import com.easylinkin.linkappapi.meterbilling.service.MeterDeviceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: linkapp-group
 * @description: 能耗查询
 * @author: chenkaixuan
 * @create: 2021-07-15 10:47
 */
@Slf4j
@Service
public class EnergyConsumptionServiceImpl implements EnergyConsumptionService {
    @Resource
    MeterDeviceConfigService meterDeviceConfigService;

    ESconfig eSconfig;
    @Autowired
    public void setESconfig(ESconfig eSconfig) {
        this.eSconfig = eSconfig;
    }


    @Override
    public Page page(Page page, EnergyConsumption energyConsumption){
        //复制属性
        MeterDeviceConfig meterDeviceConfig=new MeterDeviceConfig();
        meterDeviceConfig.setRoomId(energyConsumption.getRoomId());
        meterDeviceConfig.setMeterType(energyConsumption.getMeterType());
        meterDeviceConfig.setRoomName(energyConsumption.getRoomName());
        List<MeterDeviceConfig> meterDeviceConfigList = meterDeviceConfigService.getMeterDeviceConfigList(page, meterDeviceConfig).getRecords();
        if(meterDeviceConfigList == null || meterDeviceConfigList.size()<=0){
            return page;
        }
        List<EnergyConsumption> energyConsumptionDate = getEnergyConsumptionDateSupplement(page, energyConsumption, meterDeviceConfigList);
        page.setRecords(energyConsumptionDate);
        return page;
    }

    @Override
    public List<EnergyConsumption>  getEnergyConsumptionDateSupplement(Page page,EnergyConsumption energyConsumption,List<MeterDeviceConfig> meterDeviceConfigList){
        List<EnergyConsumption> energyConsumptionDate = getEnergyConsumptionDateNew(page, energyConsumption, meterDeviceConfigList);
        if(energyConsumptionDate == null){
            return null;
        }
//        String yyyymmddDate = DateUtil.getYYYYMMDDDate(new Date());
//        String yyyymmddDateEnd = DateUtil.getYYYYMMDDDate(energyConsumption.getQueryPayTimeStart());
//        if(yyyymmddDate.equals(yyyymmddDateEnd)){
//            return energyConsumptionDate;
//        }
        energyConsumption.setQueryPayTimeEnd(energyConsumption.getQueryPayTimeStart());
        energyConsumption.setQueryPayTimeStart(null);
        //补充
        List<EnergyConsumption> energyConsumptionDateSupplement =getEnergyConsumptionDateNew(page, energyConsumption, meterDeviceConfigList);
        if(energyConsumptionDateSupplement == null){
            return energyConsumptionDate;
        }
        Map<String, EnergyConsumption> energyConsumptionMap = energyConsumptionDateSupplement.stream().collect(Collectors.toMap(m -> m.getDeviceCode(), m -> m, (m1, m2) -> m1));
        energyConsumptionDate=energyConsumptionDate.stream().map(m->{
            EnergyConsumption consumption = energyConsumptionMap.get(m.getDeviceCode());
            if(consumption == null){
                return m;
            }
            if(StringUtils.isEmpty(consumption.getEndRead())){
                m.setStartRead(BigDecimal.ZERO);
            }else{
                m.setStartRead(consumption.getEndRead());
            }
            m.setStartReadName(consumption.getEndReadName());
            if(!StringUtils.isEmpty(m.getStartRead()) && !StringUtils.isEmpty(m.getEndRead())){
                m.setAmount(m.getEndRead().subtract(m.getStartRead(),MathContext.DECIMAL32));
            }else {
                m.setAmount(new BigDecimal(0.0));
            }
            return m;
        }).collect(Collectors.toList());
        return energyConsumptionDate;
    }

    /***
     * 导出
     * @param energyConsumption
     * @param request
     * @param response
     */
    @Override
    public void exportData(EnergyConsumption energyConsumption, HttpServletRequest request, HttpServletResponse response) {
        //复制属性
        MeterDeviceConfig meterDeviceConfig=new MeterDeviceConfig();
        meterDeviceConfig.setRoomId(energyConsumption.getRoomId());
        meterDeviceConfig.setMeterType(energyConsumption.getMeterType());
        meterDeviceConfig.setRoomName(energyConsumption.getRoomName());
        List<MeterDeviceConfig> meterDeviceConfigList = meterDeviceConfigService.getMeterDeviceConfigList(meterDeviceConfig);
        Assert.notEmpty(meterDeviceConfigList,"根据条件查得需要导出的数据为空");
        List<EnergyConsumption> energyConsumptionDate = getEnergyConsumptionDateSupplement(null, energyConsumption, meterDeviceConfigList);
        String keyValue = "房间:roomName,设备类型:MeterTypeName,起始读数:startReadName,截止读数:endReadName,用量:amount";
        String title = "能耗查询";
        String fileName = title + ".xls";
        try {
            List<String> stringList = new ArrayList<String>();
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportBankExcelV2(outputStream, keyValue, energyConsumptionDate, ExcelConstant.XLS, title, stringList);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败");
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    public List<EnergyConsumption> getEnergyConsumptionDateNew(Page page,EnergyConsumption energyConsumption,List<MeterDeviceConfig> meterDeviceConfigList){
        if(page == null){
            page=new Page(1,9999);
        }
        //获取所有设备
        List<String> collect = meterDeviceConfigList.stream().map(i -> i.getDeviceCode()).collect(Collectors.toList());
        HashMap<String, EnergyConsumption> deviceDataListFromES = getDeviceDataListFromESNew(collect,
                (int) page.getCurrent(),
                (int) page.getSize(),
                DateUtil.getYYYYMMDDHHMMSSDate(energyConsumption.getQueryPayTimeStart()),
                DateUtil.getYYYYMMDDHHMMSSDate(energyConsumption.getQueryPayTimeEnd()),
                Arrays.asList("positive_active_energy", "water_flux"));

        List<EnergyConsumption> energyConsumptionList =meterDeviceConfigList.stream().map(mdc->{
            EnergyConsumption value = null;
            if(deviceDataListFromES != null && deviceDataListFromES.size()>0){
                value=deviceDataListFromES.get(mdc.getDeviceCode());
            }
            if(StringUtils.isEmpty(value)){
                value=new EnergyConsumption();
            }
            if(!StringUtils.isEmpty(value.getStartRead()) && !StringUtils.isEmpty(value.getEndRead())){
                value.setAmount(value.getEndRead().subtract(value.getStartRead(),MathContext.DECIMAL32));
            }else {
                value.setAmount(new BigDecimal(0.0));
            }
            value.setDeviceCode(mdc.getDeviceCode());
            value.setRoomId(mdc.getRoomId());
            value.setRoomName(mdc.getRoomName());
            value.setMeterType(mdc.getMeterType());
            value.setMeterTypeName(mdc.getMeterTypeName());
            return value;
        }).collect(Collectors.toList());
        return  energyConsumptionList;
    }

    @Override
    public List<EnergyConsumption> getEnergyConsumptionDate(Page page,EnergyConsumption energyConsumption,List<MeterDeviceConfig> meterDeviceConfigList){
        if(page == null){
            page=new Page(1,9999);
        }
        //获取所有设备
        List<String> collect = meterDeviceConfigList.stream().map(i -> i.getDeviceCode()).collect(Collectors.toList());
        HashMap<String, EnergyConsumption> deviceDataListFromES = getDeviceDataListFromES(collect,
                (int) page.getCurrent(),
                (int) page.getSize(),
                DateUtil.getYYYYMMDDHHMMSSDate(energyConsumption.getQueryPayTimeStart()),
                DateUtil.getYYYYMMDDHHMMSSDate(energyConsumption.getQueryPayTimeEnd()),
                Arrays.asList("positive_active_energy", "water_flux"));

        List<EnergyConsumption> energyConsumptionList =meterDeviceConfigList.stream().map(mdc->{
            EnergyConsumption value = null;
            if(deviceDataListFromES != null && deviceDataListFromES.size()>0){
                value=deviceDataListFromES.get(mdc.getDeviceCode());
            }
            if(StringUtils.isEmpty(value)){
                value=new EnergyConsumption();
            }
            if(!StringUtils.isEmpty(value.getStartRead()) && !StringUtils.isEmpty(value.getEndRead())){
                 value.setAmount(value.getEndRead().subtract(value.getStartRead(),MathContext.DECIMAL32));
            }else {
                value.setAmount(new BigDecimal(0.0));
            }
            value.setDeviceCode(mdc.getDeviceCode());
            value.setRoomId(mdc.getRoomId());
            value.setRoomName(mdc.getRoomName());
            value.setMeterType(mdc.getMeterType());
            value.setMeterTypeName(mdc.getMeterTypeName());
            value.setQueryPayTimeStart(energyConsumption.getQueryPayTimeStart());
            value.setQueryPayTimeEnd(energyConsumption.getQueryPayTimeEnd());
            return value;
        }).collect(Collectors.toList());
        return  energyConsumptionList;
    }

    public HashMap<String, EnergyConsumption> getDeviceDataListFromES(List<String> deviceCodeList,int index, int size,String beginTime, String endTime,List<String> necessaryFieldList){
        if(deviceCodeList == null || deviceCodeList.size()<=0){
            return null;
        }
        QueryBuilder boolquery = QueryBuilders.boolQuery();
        if (!CollectionUtils.isEmpty(necessaryFieldList)) {
            necessaryFieldList.forEach(item -> {
//                属性状态值 挪到了 data之下
                QueryBuilder existQuery = QueryBuilders.existsQuery("data." + item);
                ((BoolQueryBuilder) boolquery).should(existQuery);
            });
        }
        index--;
        // es 6.0以上支持RestHighLevelClient
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();

//        获取索引,这个月和上个月的 deviceflow-202101,deviceflow-202012
        String indices = EsCalendar.getDeviceFlowIndex(2);
//        String indices = "deviceflow-202108-lqh";
        SearchRequest searchRequest = new SearchRequest(indices);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 查询条件，可以参考官网手册
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        Assert.notEmpty(deviceCodeList, "查询Es，设备编号不能为空!");
        boolQuery.must(QueryBuilders.termsQuery("deviceCode", deviceCodeList));
        boolQuery.must(boolquery);

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createTime").format("yyyy-MM-dd HH:mm:ss");

        if(!StringUtils.isEmpty(beginTime)){
            rangeQueryBuilder.gte(beginTime);
        }
        if(!StringUtils.isEmpty(endTime)){
            rangeQueryBuilder.lte(endTime);
        }
        boolQuery.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQuery);
        String[] includeFields = new String[]{};
        String[] excludeFields = new String[]{"sourceRef"};
        searchSourceBuilder.fetchSource(includeFields, excludeFields);

        TermsAggregationBuilder groupby_cteateTimeMax=AggregationBuilders
                .terms("groupby_cteateTimeMax").field("deviceCode").size(deviceCodeList.size())
                .order(BucketOrder.key(false))
                .subAggregation(AggregationBuilders.max("createTimeMax").field("createTime"))
                .executionHint("map");
        //查询最大值所有数据
        AggregationBuilder top_score_member_Max= AggregationBuilders.topHits("top_score_member_Max").sort("createTime",SortOrder.DESC).size(1);
        groupby_cteateTimeMax.subAggregation(top_score_member_Max);

        //插叙最小
        TermsAggregationBuilder groupby_cteateTimeMin=AggregationBuilders.terms("groupby_cteateTimeMin").field("deviceCode")
                .order(BucketOrder.key(true)).size(deviceCodeList.size())
                .subAggregation(AggregationBuilders.min("createTimeMin").field("createTime"))
                .executionHint("map");
        //查询最小值所有数据
        AggregationBuilder top_score_member_Min= AggregationBuilders.topHits("top_score_member_Min").sort("createTime",SortOrder.ASC).size(1);
        groupby_cteateTimeMin.subAggregation(top_score_member_Min);

        //添加聚合条件
        searchSourceBuilder.aggregation(groupby_cteateTimeMax);
        searchSourceBuilder.aggregation(groupby_cteateTimeMin);
        searchSourceBuilder.trackTotalHits(true);

        searchSourceBuilder.from(index * size).size(size);
        searchSourceBuilder.sort("createTime", SortOrder.DESC);
        searchRequest.source(searchSourceBuilder);
        //聚合求值
        Map<String,Object> map=null;
        Aggregations aggregations;
        HashMap<String, EnergyConsumption> energyConsumptionHashMap = new HashMap<>();
        try {
            log.info("设备数据详情ES请求数据：" + searchRequest.toString());
            SearchResponse searchResponse = hclient.search(searchRequest, RequestOptions.DEFAULT);
            aggregations=searchResponse.getAggregations();
            //获取最大
            Terms groupby_cteateTimeTermsMax=aggregations.get("groupby_cteateTimeMax");
            List<? extends Terms.Bucket> bucketMax=groupby_cteateTimeTermsMax.getBuckets();
            for(Terms.Bucket bucket : bucketMax){
                TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Max");
                SearchHit searchHit = topScoreResult.getHits().getAt(0);
                map=searchHit.getSourceAsMap();
                setEnergyConsumption(map,energyConsumptionHashMap,true);
            }

            //最小
            Terms groupby_cteateTimeTermsMin=aggregations.get("groupby_cteateTimeMin");
            List<? extends Terms.Bucket> bucketMin=groupby_cteateTimeTermsMin.getBuckets();
            for(Terms.Bucket bucket : bucketMin){
                TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Min");
                SearchHit searchHit = topScoreResult.getHits().getAt(0);
                map=searchHit.getSourceAsMap();
                setEnergyConsumption(map,energyConsumptionHashMap,false);
            }

        } catch (Exception e) {
            log.error("getDeviceDataListFromES 搜索ES数据,索引:" + indices + "异常message:{}", e);
            return null;
        }
        return  energyConsumptionHashMap;
    }

    /***
     * 新增加查询es数据，按需统计数值取最大最小
     * @param deviceCodeList
     * @param index
     * @param size
     * @param beginTime
     * @param endTime
     * @param necessaryFieldList
     * @return
     */
    public HashMap<String, EnergyConsumption> getDeviceDataListFromESNew(List<String> deviceCodeList,int index, int size,String beginTime, String endTime,List<String> necessaryFieldList){
        if(deviceCodeList == null || deviceCodeList.size()<=0){
            return null;
        }
        QueryBuilder boolquery = QueryBuilders.boolQuery();
        if (!CollectionUtils.isEmpty(necessaryFieldList)) {
            necessaryFieldList.forEach(item -> {
//                属性状态值 挪到了 data之下
                QueryBuilder existQuery = QueryBuilders.existsQuery("data." + item);
                ((BoolQueryBuilder) boolquery).should(existQuery);
            });
        }
        index--;
        // es 6.0以上支持RestHighLevelClient
        RestHighLevelClient hclient = eSconfig.getFactory().getRhlClient();

//        获取索引,这个月和上个月的 deviceflow-202101,deviceflow-202012
        String indices = EsCalendar.getDeviceFlowIndex(2);
        SearchRequest searchRequest = new SearchRequest(indices);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 查询条件，可以参考官网手册
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        Assert.notEmpty(deviceCodeList, "查询Es，设备编号不能为空!");
        boolQuery.must(QueryBuilders.termsQuery("deviceCode", deviceCodeList));
        boolQuery.must(boolquery);

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createTime").format("yyyy-MM-dd HH:mm:ss");

        if(!StringUtils.isEmpty(beginTime)){
            rangeQueryBuilder.gte(beginTime);
        }
        if(!StringUtils.isEmpty(endTime)){
            rangeQueryBuilder.lte(endTime);
        }
        boolQuery.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQuery);
        String[] includeFields = new String[]{};
        String[] excludeFields = new String[]{"sourceRef"};
        searchSourceBuilder.fetchSource(includeFields, excludeFields);

        TermsAggregationBuilder groupby_cteateTimeMax=AggregationBuilders
                .terms("groupby_cteateTimeMax").field("deviceCode").size(deviceCodeList.size())
                .order(BucketOrder.key(false))
                .executionHint("map");
        //插叙最小
        TermsAggregationBuilder groupby_cteateTimeMin=AggregationBuilders.terms("groupby_cteateTimeMin").field("deviceCode")
                .order(BucketOrder.key(true)).size(deviceCodeList.size())
                .executionHint("map");
        for (String item : necessaryFieldList) {
            //查询最大值所有数据
            MaxAggregationBuilder createTimeMax = AggregationBuilders.max("createTimeMax"+item).field("data." + item);
            AggregationBuilder top_score_member_Max= AggregationBuilders.topHits("top_score_member_Max"+item).sort("data." + item,SortOrder.DESC).size(1);
            groupby_cteateTimeMax.subAggregation(createTimeMax);
            groupby_cteateTimeMax.subAggregation(top_score_member_Max);
            //查询最小值所有数据
            MinAggregationBuilder createTimeMin = AggregationBuilders.min("createTimeMin"+item).field("data." + item);
            AggregationBuilder top_score_member_Min= AggregationBuilders.topHits("top_score_member_Min"+item).sort("createTime",SortOrder.ASC).size(1);
            groupby_cteateTimeMax.subAggregation(createTimeMin);
            groupby_cteateTimeMin.subAggregation(top_score_member_Min);

        }
        //添加聚合条件
        searchSourceBuilder.aggregation(groupby_cteateTimeMax);
        searchSourceBuilder.aggregation(groupby_cteateTimeMin);
        searchSourceBuilder.trackTotalHits(true);

        searchSourceBuilder.from(index * size).size(size);
        searchSourceBuilder.sort("createTime", SortOrder.DESC);
        searchRequest.source(searchSourceBuilder);
        //聚合求值
        Map<String,Object> map=null;
        Aggregations aggregations;
        HashMap<String, EnergyConsumption> energyConsumptionHashMap = new HashMap<>();
        try {
            log.info("设备数据详情ES请求数据：" + searchRequest.toString());
            SearchResponse searchResponse = hclient.search(searchRequest, RequestOptions.DEFAULT);
            aggregations=searchResponse.getAggregations();
            //获取最大
            Terms groupby_cteateTimeTermsMax=aggregations.get("groupby_cteateTimeMax");
            List<? extends Terms.Bucket> bucketMax=groupby_cteateTimeTermsMax.getBuckets();
            for(Terms.Bucket bucket : bucketMax){
                for (String item : necessaryFieldList) {
                    Max max = bucket.getAggregations().get("createTimeMax" + item);
                    if(max == null){
                        continue;
                    }
                    Double maxValue = Double.valueOf(max.getValue());
                    if(maxValue == null || maxValue.isInfinite()){
                        continue;
                    }
                    TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Max"+item);
                    if(topScoreResult == null ||topScoreResult.getHits() == null || topScoreResult.getHits().getHits() == null){
                        continue;
                    }
                    SearchHit searchHit = topScoreResult.getHits().getAt(0);
                    map=searchHit.getSourceAsMap();
                    setEnergyConsumption(map,energyConsumptionHashMap,true);
                }
            }

            //最小
            Terms groupby_cteateTimeTermsMin=aggregations.get("groupby_cteateTimeMin");
            List<? extends Terms.Bucket> bucketMin=groupby_cteateTimeTermsMin.getBuckets();
            for(Terms.Bucket bucket : bucketMin){
                for (String item : necessaryFieldList) {
                    Min min = bucket.getAggregations().get("createTimeMin" + item);
                    if(min == null){
                        continue;
                    }
                    Double minValue = Double.valueOf(min.getValue());
                    if(minValue == null || minValue.isInfinite()){
                        continue;
                    }
                    TopHits topScoreResult  = bucket.getAggregations().get("top_score_member_Min"+item);
                    if(topScoreResult == null ||topScoreResult.getHits() == null || topScoreResult.getHits().getHits() == null){
                        continue;
                    }
                    SearchHit searchHit = topScoreResult.getHits().getAt(0);
                    map=searchHit.getSourceAsMap();
                    setEnergyConsumption(map,energyConsumptionHashMap,false);
                }
            }

        } catch (Exception e) {
            log.error("getDeviceDataListFromESNew 搜索ES数据,索引:" + indices + "异常message:{}", e);
            return null;
        }
        return  energyConsumptionHashMap;
    }


    private  void  setEnergyConsumption(Map<String,Object> map,HashMap<String, EnergyConsumption> energyConsumptionHashMap,boolean falg){
        if(map == null){
            return;
        }
        if(StringUtils.isEmpty(map.get("deviceCode"))){
            return;
        }
        String deviceCode = String.valueOf(map.get("deviceCode"));
        EnergyConsumption energyConsumption = energyConsumptionHashMap.get(deviceCode);
        if(StringUtils.isEmpty(energyConsumption)){
            energyConsumption=new EnergyConsumption();
        }
        //只有一条数据直接赋值
        HashMap data=(HashMap)map.get("data");
        if(data == null){
            return;
        }
        Object positive_active_energy = data.get("positive_active_energy");
        if(!StringUtils.isEmpty(positive_active_energy)){
            Double active_energy = Double.valueOf(String.valueOf(data.get("positive_active_energy")));
            if(falg){
                energyConsumption.setEndReadName(active_energy+"度");
                energyConsumption.setEndRead(BigDecimal.valueOf(active_energy));
            }else{
                energyConsumption.setStartReadName(active_energy+"度");
                energyConsumption.setStartRead(BigDecimal.valueOf(active_energy));
            }
        }
        Object water_flux = data.get("water_flux");
        if(!StringUtils.isEmpty(water_flux)){
            Double active_energy =Double.valueOf(String.valueOf(data.get("water_flux")));
            if(falg){
                energyConsumption.setEndReadName(active_energy+"吨");
                energyConsumption.setEndRead(BigDecimal.valueOf(active_energy));
            }else{
                energyConsumption.setStartReadName(active_energy+"吨");
                energyConsumption.setStartRead(BigDecimal.valueOf(active_energy));
            }
        }
        energyConsumptionHashMap.put(deviceCode,energyConsumption);
    }
}
